import { onMounted, reactive, watch } from 'vue'

export function useAuth(){
    const user=reactive({
        username:'',
        token:null,
        islogin:false
    })
    // 登录
    const login=(token,username)=>{
        user.token=token
        user.username=username
        user.islogin=true
    }
    // 登出
    const logout=()=>{
        user.token=null
        user.username=''
        user.islogin=false
    }

    // 验证token
    const authStatus=async()=>{
        // 获取保存token
        const savedToken=localStorage.getItem('atuToken')
        if(savedToken){
            setTimeout(()=>{
                if(savedToken==='val-token'){
                    login(savedToken,'授权用户')
                }else{
                    logout()
                }
            },500)
        }else{
            logout()
        }
    }
    onMounted(authStatus)
    // 侦听token
    watch(()=>user.token,(newToken)=>{
        if(!newToken){
            logout()
            localStorage.removeItem('atuToken')
        }else{
            localStorage.setItem('atuToken',newToken)
        }
    })


    return {
        user,
        login,
        logout
    }
}